﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Xml;
using System.Globalization;


public partial class EditGalery : System.Web.UI.Page
{

     string[] PictureList = new string[0]; //[fotoFile.Length];
    int MapesNr = 0;

    internal class CustomCompare : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return DateTime.Compare(
              Directory.GetCreationTime(y), Directory.GetCreationTime(x));
        }
    } 
    protected void Page_Load(object sender, EventArgs e)
    {
    //    if (User.Identity.IsAuthenticated == false)
    //    { Server.Transfer("login_aizliegts.aspx"); }
    //    else
    //    {
               // string virtualPathDir = Server.MapPath("~/galerijas/"); // atrod virtual path lapas Bāzes MAPI
                //string[] dirrAray = Directory.GetDirectories(virtualPathDir); // nolasa visas servera Mapes
                //Array.Sort(dirrAray, new CustomCompare()); // Sortēšana
                //string[] dirrArray2 = new string[dirrAray.Length];
                //int cipars = 0; // Sagrupē mapes tā lai jaunākā ir pēdējā !!
                //for (int i = dirrAray.Length; i > 0; i--)
                //{
                //    dirrArray2[cipars] = dirrAray[i - 1];
                //    cipars++;
                //}
                MapesNr = Convert.ToInt16(String.Format(Request.QueryString["value"]));
       
                string virtualPathDir2 = Server.MapPath("~/"); 
                DataTable galery = new DataTable("galery");
                galery.ReadXml(virtualPathDir2 + "galery.xml");
                int a=0;
                foreach (DataRow Dr in galery.Rows)
                {
                    if ((int)Dr[1] == MapesNr)
                    {
                        Array.Resize(ref PictureList, a+1);
                        PictureList[a] = (string)Dr[5];
                            a++;
                    }
                }
               


                if (Page.IsPostBack == false)
                {
                    Repeater1.DataSource = PictureList;
                    Repeater1.DataBind();
                }
       
        //}
    }
    protected void Repeater1_ItemCommand2(object source, RepeaterCommandEventArgs e)
    {
        int nummurs = e.Item.ItemIndex;
        string[] TextGab = PictureList[nummurs].Split('/');
        if (MapesNr < 10)
        {
            string serchBiggPic = "0" + Convert.ToString(MapesNr) + TextGab[5].Substring(5);

            Response.Redirect("EditGaleryZoom.aspx?value=" + serchBiggPic);
        }
        else
        {
            string serchBiggPic = Convert.ToString(MapesNr) + TextGab[5].Substring(5);

            Response.Redirect("EditGaleryZoom.aspx?value=" + serchBiggPic);
        }   

    }
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {

    }




    public void CreateXMLshemaGalery(DataTable SendBarcode, string Filename)
    {
        Type[] BarcodeCollons = { typeof(System.Int32),
                                       typeof(System.Int32),
                                       typeof(System.String),
                                       typeof(System.DateTime),
                                       typeof(System.String),
                                       typeof(System.String),
                                       typeof(System.String) };
    string[] kolonName = { "ID","MapID", "NAME", "DATE", "IMG","IMGsmall", "TEXT" };
                                       
        WriteXML_SHemaAndData(kolonName,SendBarcode, BarcodeCollons,Filename);
    }

    public void CreateXMLshemaMape(DataTable SendBarcode,string Filename)
    {
        Type[] BarcodeCollons = { typeof(System.Int32),
                                       typeof(System.String),
                                       typeof(System.DateTime),
                                       typeof(System.String) };
        string[] kolonName = { "ID", "NAME", "DATE", "TEXT" };

        WriteXML_SHemaAndData(kolonName, SendBarcode, BarcodeCollons,Filename);
    }
    public void WriteXML_SHemaAndData(string[] k, DataTable DTx, Type[] Collons, string Filename)
    {
        // Uztaisa Test DataTable un DataSetu ar Barcode Tablu
        New_SendORder_dataTable(k, DTx, Collons);
        Add_SendORder_DataRow(k, DTx, Collons);
        DataSet ds = new DataSet(DTx.TableName + "Ds");
        ds.Tables.Add(DTx);

        // EXMPLE nokopēts no  http://msdn.microsoft.com/en-us/library/360dye2a.aspx
        // Write the XML schema and data to file with FileStream.
        string virtualPathDir = Server.MapPath("~/"); 
        string xmlFilename = virtualPathDir + Filename;  // DTx.TableName + ".xml";

        ds.WriteXml(xmlFilename, XmlWriteMode.WriteSchema);
        ds.Dispose();
    }

    public DataTable New_SendORder_dataTable(string[] kk, DataTable Tx, Type[] Tips)
    {
        Tx.Clear();
        int count = kk.Length;
        DataColumn[] dc = new DataColumn[count];
        for (int i = 0; i < kk.Length; i++)
        {
            dc[i] = new DataColumn();
            dc[i].DataType = Tips[i]; // Type.GetType("System.String");
            dc[i].ColumnName = kk[i];
            Tx.Columns.Add(dc[i]);
            if (i == 0) // Set PRimary Key Collumn
            {
                DataColumn[] Pkey = new DataColumn[1]; // uztaisa jaunu Datu kolonu ar 1nu vertību, un tajā ieliek pirmo Datu kolonu.
                Pkey[0] = dc[0];
                Tx.PrimaryKey = Pkey; // inicializē Vienu 1 Primary.Key kollonu
            }
        }
        return Tx;
    }

    public DataTable Add_SendORder_DataRow(string[] kk, DataTable Tx, Type[] Tips)
    {
        IFormatProvider culture = new CultureInfo("en-GB", true);

        DataRow Trow = Tx.NewRow();
        for (int i = 0; i < kk.Length; i++)
        {
            if (Tips[i] == typeof(System.Int32))
            {
                Trow[i] = 1;
            }
            else if (Tips[i] == typeof(System.String))
            {
                Trow[i] = "Test";
            }
            else if (Tips[i] == typeof(System.Double))
            {
                try
                {
                    Trow[i] = 1;
                }
                catch (FormatException)
                {

                    Trow[i] = 1; //convertTodouble(Xnode.Attributes[i].Value);
                }
            }
            else if (Tips[i] == typeof(System.DateTime))
            {
                try
                {
                    Trow[i] = DateTime.Now; // Convert.ToDateTime(Xnode.Attributes[i].Value, culture);
                }
                catch (FormatException)
                {
                    Trow[i] = DateTime.Now;  // convertToTime(Xnode.Attributes[i].Value);
                }
            }
            else if (Tips[i] == typeof(System.Boolean))
            {
                try
                {
                    Trow[i] = true; // Convert.ToBoolean(Xnode.Attributes[i].Value);
                }
                catch (FormatException)
                { Trow[i] = false; }
            }
        }
        lock (this) // MULTI Threading.
        {
            Tx.Rows.Add(Trow);
        }
        return Tx;
    }

    static double convertTodouble(string number)
    {
        CultureInfo culture = new CultureInfo("en-US");
        double cenap = 0;
        NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); // System.Globalization.CultureInfo.CurrentCulture.NumberFormat;
        numberFormatInfo.NumberDecimalSeparator = ".";
        numberFormatInfo.NumberGroupSeparator = " ";
        numberFormatInfo.CurrencyGroupSeparator = " ";
        numberFormatInfo.PercentGroupSeparator = " ";
        try
        {
            cenap = Convert.ToDouble(number, numberFormatInfo);  //checkStringNumber(mr[2].ToString()));
        }
        catch (FormatException er)
        {
            numberFormatInfo.CurrencyDecimalSeparator = ",";
            numberFormatInfo.NumberDecimalSeparator = ","; // megina komatu! 
            try
            {
                cenap = Convert.ToDouble(number, numberFormatInfo);
            }
            catch (FormatException f)
            {
                cenap = 0;
            }
        }
        return cenap;
    }

    static DateTime convertToTime(string Time)
    {
        DateTimeFormatInfo DateFormatInfo = new CultureInfo("en-US", false).DateTimeFormat;

        DateFormatInfo.DateSeparator = "/";
        DateFormatInfo.TimeSeparator = ":";
        DateTime laiks = Convert.ToDateTime(Time, DateFormatInfo);
        return laiks;

    }

    protected void Button1Test_Click(object sender, EventArgs e)
    {
        // Create XML shema FIles. galery un Mape. 
       //  CreateGaleryXMLfiles();   // uzģenerē tukšus galery.XML un Mape.xml
    }

    void CreateGaleryXMLfiles()
    {
        DataTable galery = new DataTable("galery");
        CreateXMLshemaGalery(galery,"galery.xml");
        DataTable Mape = new DataTable("Mape");
        CreateXMLshemaMape(Mape, "Mape.xml");
    }

    void FillGaleryXMLfiles()
    {
        string virtualPathDir2 = Server.MapPath("~/");
        DataTable galery = new DataTable("galery");
        galery.ReadXml(virtualPathDir2 + "galery.xml");
        DataTable Mape = new DataTable("Mape");
        Mape.ReadXml(virtualPathDir2 + "Mape.xml");

        string virtualPathDir = Server.MapPath("~/galerijas/"); // atrod virtual path lapas Bāzes MAPI
        string[] dirrAray = Directory.GetDirectories(virtualPathDir); // nolasa visas servera Mapes
        Array.Sort(dirrAray, new CustomCompare()); // Sortēšana
        string[] dirrArray2 = new string[dirrAray.Length];
        int cipars = 0; // Sagrupē mapes tā lai jaunākā ir pēdējā !!
        for (int i = dirrAray.Length; i > 0; i--)
        {
            dirrArray2[cipars] = dirrAray[i - 1];
            cipars++;
        }
        string virtualPathDir3 = Server.MapPath("~/");
        int charCount = virtualPathDir3.LastIndexOf("\\") + 1;

        for (int ii = 0; ii < dirrArray2.Length; ii++) // iziet cauri visām Foto mapēm.
        {
            DataRow NewR = Mape.NewRow();
            int MapID = (int)Mape.Rows[Mape.Rows.Count - 1][0] + 1;
            NewR[0] = MapID;
            NewR[1] = dirrArray2[ii].Substring(charCount); ; // mapes nosaukums.
            NewR[2] = Directory.GetCreationTime(dirrArray2[ii]);
            NewR[3] = " ";
            Mape.LoadDataRow(NewR.ItemArray, true);

            string[] fotoFile = Directory.GetFiles(dirrArray2[ii]);
            //string virtualPathDir3 = Server.MapPath("~/");
            //int charCount = virtualPathDir3.LastIndexOf("\\") + 1;

            int PicturCount = 0;
            //btn_count = fotoFile.Length;
            //string textID = "Lbutton";
            for (int i = 0; i < fotoFile.Length; i++)
            {


                string EsošaisTeksts = fotoFile[i].Substring(charCount);
                string[] TextGabali = EsošaisTeksts.Split('\\');
                bool smallimg = false;
                smallimg = TextGabali[2].Contains("Small");
                if (smallimg == false)
                {    // vispirms atrod Lielo bildi un tad meklē mazo, ja tāda ir, ja nav ta mazo neliek. 
                    DataRow NewB = galery.NewRow(); // "ID","MapID", "NAME", "DATE", "IMG","IMGsmall", "TEXT"
                    NewB[0] = (int)galery.Rows[galery.Rows.Count - 1][0] + 1;
                    NewB[1] = MapID;
                    NewB[2] = TextGabali[2];
                    NewB[3] = File.GetCreationTime(fotoFile[i]);
                    string jaunaisLinks = "";
                    for (int i2 = 0; i2 < TextGabali.Length; i2++)
                    {
                        if (i2 == TextGabali.Length - 1)
                        {
                            jaunaisLinks += TextGabali[i2];
                        }
                        else { jaunaisLinks += TextGabali[i2] + "/"; }
                    }
                    NewB[4] = "http://www.parbmx.com/" + jaunaisLinks; // TextGabali[2]; // uztaisa IMG linku. ******
                    NewB[5] = " "; // Empty
                    NewB[6] = " "; // Empty

                    for (int aa = 0; aa < fotoFile.Length; aa++)
                    {
                        // serch for small img. 
                        string EsošaisTekstsX = fotoFile[aa].Substring(charCount);
                        string[] TextGabaliX = EsošaisTekstsX.Split('\\');
                        bool smallimgX = false;
                        smallimgX = TextGabaliX[2].Contains("Small");
                        if (smallimgX == true)
                        {
                            if (TextGabaliX[2].Remove(0, 5) == TextGabali[2]) // *********
                            {
                                string jaunaisLinks2 = "";
                                for (int i2 = 0; i2 < TextGabaliX.Length; i2++)
                                {
                                    if (i2 == TextGabaliX.Length - 1)
                                    {
                                        jaunaisLinks2 += TextGabaliX[i2];
                                    }
                                    else { jaunaisLinks2 += TextGabaliX[i2] + "/"; }
                                }
                                NewB[5] = "http://www.parbmx.com/" + jaunaisLinks2; // fotoFile[aa]; // uzģenerē "Small" img linku.
                                break;
                            }
                        }
                    }
                    galery.LoadDataRow(NewB.ItemArray, true);
                    // beigas  if (smallimg != true)
                }

            }
        }

        DataSet ds = new DataSet(Mape.TableName + "Ds");
        ds.Tables.Add(Mape);
        ds.WriteXml(virtualPathDir2 + "Mape.xml", XmlWriteMode.WriteSchema);
        ds.Dispose();
        DataSet dss = new DataSet(galery.TableName + "Ds");
        dss.Tables.Add(galery);
        dss.WriteXml(virtualPathDir2 + "galery.xml", XmlWriteMode.WriteSchema);
        dss.Dispose();
    }
 

    protected void GaleryXMLupdate_Click(object sender, EventArgs e)
    {
         FillGaleryXMLfiles();  // izfiltrē visas Galerijas/ mapes un aizpilda XML failus: galery.xml un Mape.xml

    }
}
